<template>
  <el-form :model="formData" class="grid grid-cols-5 gap-4">
    <div v-for="(item, index) in formFields" :key="index">
      <el-form-item :label="item.label" :prop="item.prop">
        <component
          :is="getComponentType(item.type)"
          v-bind="item.props"
          v-model="formData[item.prop]"
        >
          <el-option
            v-if="item.type === 'select'"
            v-for="option in item.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </component>
      </el-form-item>
    </div>
  </el-form>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElDatePicker,
  ElOption,
} from "element-plus";

type FormField = {
  label: string;
  prop: string;
  type: string;
  props: Record<string, any>;
  options?: Array<{ label: string; value: string | number }>;
};

export default defineComponent({
  name: "DynamicForm",
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElDatePicker,
    ElOption,
  },
  props: {
    formFields: {
      type: Array as () => FormField[],
      required: true,
    },
  },
  setup(props) {
    // 动态表单数据
    const formData = ref<Record<string, any>>({});

    // 初始化表单数据
    props.formFields.forEach((field) => {
      formData.value[field.prop] = "";
    });

    // 获取组件类型
    const getComponentType = (type: string) => {
      switch (type) {
        case "input":
          return ElInput;
        case "select":
          return ElSelect;
        case "date":
          return ElDatePicker;
        default:
          return ElInput;
      }
    };

    return {
      formData,
      getComponentType,
    };
  },
});
</script>

<style scoped>
/* 你可以添加一些样式 */
</style>
